const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const koaBody = require('koa-body');
const session = require('koa-session');
const cors = require('koa2-cors');

const book = require('./routes/book')
const users = require('./routes/users')
const emails = require('./routes/email');
const chat = require('./routes/chat')
const order = require('./routes/order')
const trade = require('./routes/trade')
app.keys = ['secret'];

// 存放sessionId的cookie配置
let CONFIG = {
    maxAge: 86400000, // cookie有效时长
    httpOnly: false
};
// error handler
onerror(app);

app.use(cors({
    origin: (ctx) => { //设置允许来自指定域名请求
        const origin = ctx.headers.origin;
        return origin
    },
    // maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    // allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    // allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
}));
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

// logger
app.use(async(ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
});
// upload file
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 200 * 1024 * 1024
    }
}));

app.use(session(CONFIG, app));
// routes
app.use(book.routes(), book.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(emails.routes(), emails.allowedMethods())
app.use(chat.routes(), chat.allowedMethods())
app.use(order.routes(), order.allowedMethods())
app.use(trade.routes(), trade.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app